#include "cc_rtc.h"
#include "cc_wifi.h"

#if (CC_CONFIG_USE_RTC == 1)
#include "RtcDS1302.h"
#endif

#if (CC_CONFIG_USE_RTC == 1)
ThreeWire myWire(19, 21, 18); // IO, SCLK, CE
RtcDS1302<ThreeWire> ds1302_rtc(myWire);
#endif

int cc_hour = 0;
int cc_min = 0;
int cc_sec = 0;
int time_flag;
#if (CC_CONFIG_USE_WIFI)
int cc_rtc_init()
{
  struct tm timeinfo;
  // 如果配置了wifi并且wifi未连接的情况下 连接wifi

  cc_wifi_init();
  configTime(60 * 60 * 8, 0, "ntp3.aliyun.com"); // 用的阿里云的服务器

  int cnt;
  if (cc_get_wifi_state() == CC_WIFI_CONNECTED)
  {
    while (cnt++ < 3)
    {
      if (!getLocalTime(&timeinfo))
      {
        cc_log_e("Failed to obtain time\r\n");
      }
      else
      {
        time_flag = 1;
        break;
      }
      delay(500);
    }
  }

#if (CC_CONFIG_USE_RTC == 1)
  ds1302_rtc.Begin();
#endif
  if (time_flag)
  {
    cc_hour = timeinfo.tm_hour;
    cc_min = timeinfo.tm_min;
    cc_sec = timeinfo.tm_sec;
#if (CC_CONFIG_USE_RTC == 1)
    if (ds1302_rtc.GetIsWriteProtected())
    {
      ds1302_rtc.SetIsWriteProtected(false);
    }

    if (!ds1302_rtc.GetIsRunning())
    {
      ds1302_rtc.SetIsRunning(true);
    }

    RtcDateTime rtc_data_time(timeinfo.tm_year,
                              timeinfo.tm_mon,
                              timeinfo.tm_mday,
                              timeinfo.tm_hour,
                              timeinfo.tm_min,
                              timeinfo.tm_sec);
    ds1302_rtc.SetDateTime(rtc_data_time);
    RtcDateTime now = ds1302_rtc.GetDateTime();
    time_flag = 2;
#endif
    cc_log("success sync time:\r\n");
    return 1;
  }

  return -1;
}
CC_INIT_PREV_REGISTER(cc_rtc_init)

void cc_rtc_entry(void *data)
{
  struct tm timeinfo;
  while (1)
  {
    if (time_flag == 2)
    {
#if (CC_CONFIG_USE_RTC == 1)
      RtcDateTime now = ds1302_rtc.GetDateTime();
      cc_hour = ds1302_rtc.Hour();
      cc_min = ds1302_rtc.Minute();
      cc_sec = timeinfo.Second();
#endif
    }
    else if (cc_get_wifi_state() == CC_WIFI_CONNECTED)
    {
      if (getLocalTime(&timeinfo))
      {
        if (!time_flag)
        {
          time_flag = 1;
          cc_log("sync time success\r\n");
        }

        cc_hour = timeinfo.tm_hour;
        cc_min = timeinfo.tm_min;
        cc_sec = timeinfo.tm_sec;
      }
    }
    else
    {
      time_flag = 0;
    }
    cc_delay(100);
  }
}
CC_THREAD_REGISTER_ALIAS(cc_rtc_entry, 32, 2048,"rtc_entry");
#endif